#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QMouseEvent>
#include <math.h>
#include <QMessageBox>
#include <QTimer>
#include <QDebug>
#include <QApplication>
#include <QWidget>
#include <QPushButton>



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QObject::connect(manager, &QNetworkAccessManager::finished,//λ函数表达式
             this, [=](QNetworkReply *reply)
              {
                 if (reply->error())//
                 {
                     qDebug() << reply->errorString();
                     return;
                 }

                 QString answer = reply->readAll();
                 QJsonDocument jsonResponse = QJsonDocument::fromJson(answer.toUtf8());
                 QJsonObject jsonObject = jsonResponse.object();

                 auto mode = jsonObject["mode"].toInt();
                 if(mode == 1)
                 {
                     //返回值1，为userID
                     userID = jsonObject["userID"].toString();
                 }
                 else if(mode == 2)
                 {
                     //返回值2，说明获取数据列表
                     int px1,py1;
                     QString px = "null",py="null";
                     QJsonArray jsonArray = jsonObject["operationList"].toArray();
                     foreach (const QJsonValue & value, jsonArray)
                     {
                         QJsonObject obj = value.toObject();
                         if(obj["userID"].toString() != userID)
                         {
                                px1 = obj["x"].toInt();
                                py1 = obj["y"].toInt();
                         }
                     }
                     game->actionBynet(px1,py1);

                     //最后一个数据肯定是最新的
                 }
                 else if(mode == 3)
                 {
                     //返回值3，提交坐标成功
                     QMessageBox::information(this,"alert","提交坐标成功");
                 }
                 qDebug() << answer;
             }
         );

       //向服务器注册，获取userID

     QString url = "http://43.134.52.25:30000/getUserID";
     request.setUrl(QUrl(url));
     manager->get(request);

     QTimer *timer = new QTimer(this);
     connect(timer, SIGNAL(timeout()), this, SLOT(update1()));
     timer->start(1000); //每一秒抓取一次数据




    this->setFixedSize(
     MARGIN*2+BLOCK_SIZE*BOARD_GRAD_SIZE,
     MARGIN*2+BLOCK_SIZE*BOARD_GRAD_SIZE);
}

MainWindow::~MainWindow()
{
    delete ui;//删除界面
}

void MainWindow::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing); //设置抗锯齿

    for(int i=0;i<BOARD_GRAD_SIZE+1;i++)
    {

        painter.drawLine(MARGIN+BLOCK_SIZE*i,MARGIN,
                         MARGIN+BLOCK_SIZE*i,this->height()-MARGIN);
        //从上到下，第(i+1)横线
        painter.drawLine(MARGIN,MARGIN+BLOCK_SIZE*i,
                         this->width()-MARGIN,MARGIN+BLOCK_SIZE*i);//绘图
    }

    QBrush brush;//绘制鼠标目前的点位
    brush.setStyle(Qt::SolidPattern);
    //防止鼠标出界
    if(clickPosRow>0 && clickPosRow<BOARD_GRAD_SIZE &&
       clickPosCol>0 && clickPosCol<BOARD_GRAD_SIZE &&
        game->gameMapVec[clickPosRow][clickPosCol]==0)
    {

        if(game->playerFlag){
            brush.setColor(Qt::black);
        }
        else
        {
            brush.setColor(Qt::white);
        }
        painter.setBrush(brush);
        painter.drawRect(MARGIN+BLOCK_SIZE*clickPosCol-MARK_SIZE/2,MARGIN+BLOCK_SIZE*clickPosRow-MARK_SIZE/2,MARK_SIZE,MARK_SIZE);
    }
    for(int i=0;i<BOARD_GRAD_SIZE;i++){
        for(int j=0;j<BOARD_GRAD_SIZE;j++){
            if(game->gameMapVec[i][j]==1){
                brush.setColor(Qt::black);
                painter.setBrush(brush);
                painter.drawEllipse(MARGIN+BLOCK_SIZE*j-CHESS_RADIUS,MARGIN+BLOCK_SIZE*i-CHESS_RADIUS,CHESS_RADIUS*2,CHESS_RADIUS*2);
            }
            else if(game->gameMapVec[i][j]==-1)
            {
                brush.setColor(Qt::white);
                painter.setBrush(brush);
                painter.drawEllipse(MARGIN+BLOCK_SIZE*j-CHESS_RADIUS,MARGIN+BLOCK_SIZE*i-CHESS_RADIUS,CHESS_RADIUS*2,CHESS_RADIUS*2);
            }

        }
    }
    //判断输赢
    if(clickPosCol>0 && clickPosCol<BOARD_GRAD_SIZE &&
       clickPosRow>0 && clickPosRow<BOARD_GRAD_SIZE &&
       (game->gameMapVec[clickPosRow][clickPosCol]==1||game->gameMapVec[clickPosRow][clickPosCol]==-1))
    {  //代碼解析：game->gameMapVec[clickPosRow][clickPosCol]==1||game->gameMapVec[clickPosRow][clickPosCol]==-1，防止因為5個0(空白)相連也被判勝利
        if(game->isWin(clickPosRow,clickPosCol) && game->gameStatus == PLAYING){
            game->gameStatus = WIN;
            QString str;
            str = game->gameMapVec[clickPosRow][clickPosCol]==1?"黑棋":"白棋";
            QMessageBox::StandardButton btnValue = QMessageBox::information(this,"五子棋嬴家",str+"获得胜利");
            if(btnValue == QMessageBox::Ok){
                game->startGame(game_type);
                game->gameStatus = PLAYING;
            }

        }
    }
}
//初始化




void MainWindow::initGame(){
    game = new GameModel();
    //QMessageBox::StandardButton select = QMessageBox::question(this,"選擇遊戲模式","YES[玩家VS電腦]  NO[玩家VS玩家]");

      /*QWidget widget(this);
      widget.setWindowTitle(f"best fivechess");
      QPushButton but1("genrenwan",&widget),
                  but2("gendiannaowan",&widget),
                  but3("lianwangwan",&widget),
                  but4("guanzhan",&widget);
      but1.move(50,50);
      but2.move(150,50);
      but3.move(50,150);
      but4.move(150,150);
      but1.setStyleSheet("QPushButton{font:20px;}");
      but2.setStyleSheet("QPushButton{font:20px;}");
      but3.setStyleSheet("QPushButton{font:20px;}");
      but4.setStyleSheet("QPushButton{font:20px;}");
      but1.resize(60,60);
      but2.resize(60,60);
      but3.resize(60,60);
      but4.resize(60,60);
    QObject::connect(&but1,&QPushButton::clicked,this,&typem);
    QObject::connect(&but2,&QPushButton::clicked,this,&typea);
    QObject::connect(&but3,&QPushButton::clicked,this,&typen);
    QObject::connect(&but4,&QPushButton::clicked,this,&typew);

    /*if(select == QMessageBox::Yes){
        game_type = AI;
    }else {
        game_type = MAN;
    }*/
    game_type = temtype;
    game->gameStatus = PLAYING;


    game->startGame(game_type);

    update();

   // widget.show();
}



void MainWindow::mouseMoveEvent(QMouseEvent* event){
    //确定鼠标位置
    int x = event->x();
    int y = event->y();

    //棋盘边缘不能落子，方法同上次的实现方法
    if(x>=MARGIN+BLOCK_SIZE/2&&
           x<this->width()-MARGIN-BLOCK_SIZE/2&&
           y>=MARGIN+BLOCK_SIZE/2&&
           y<this->height()-MARGIN-BLOCK_SIZE/2){

        int col = (x-MARGIN)/BLOCK_SIZE;
        int row = (y-MARGIN)/BLOCK_SIZE;

        int leftTopPosX = MARGIN+BLOCK_SIZE*col;
        int leftTopPosY = MARGIN+BLOCK_SIZE*row;


        clickPosRow = -1; //最终值初始化
        clickPosCol = -1;
        int len = 0;
        selectPos = false;


        len = sqrt((x-leftTopPosX)*(x-leftTopPosX)+(y-leftTopPosY)*(y-leftTopPosY));
        if(len<POS_OFFSET){
            clickPosRow = row;
            clickPosCol = col;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0){
                selectPos = true;
            }
        }

        len = sqrt((x-leftTopPosX-BLOCK_SIZE)*(x-leftTopPosX-BLOCK_SIZE)+(y-leftTopPosY)*(y-leftTopPosY));
        if(len<POS_OFFSET){
            clickPosRow = row;
            clickPosCol = col+1;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0){
                selectPos = true;
            }
        }

        len = sqrt((x-leftTopPosX)*(x-leftTopPosX)+(y-leftTopPosY-BLOCK_SIZE)*(y-leftTopPosY-BLOCK_SIZE));
        if(len<POS_OFFSET){
            clickPosRow = row+1;
            clickPosCol = col;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0){
                selectPos = true;
            }
        }

        len = sqrt((x-leftTopPosX-BLOCK_SIZE)*(x-leftTopPosX-BLOCK_SIZE)+(y-leftTopPosY-BLOCK_SIZE)*(y-leftTopPosY-BLOCK_SIZE));
        if(len<POS_OFFSET)
        {
            clickPosRow = row+1;
            clickPosCol = col+1;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0){
                selectPos = true;
            }
        }
    }

    update();//重新绘制棋盘
}

void MainWindow::mouseReleaseEvent(QMouseEvent* event){
    if(selectPos == false){
        return;
    }
    else
    {
        selectPos = false;
    }
    //由人來下棋
    chessOneByPerson();
    if(game_type == AI)
    {

        QTimer::singleShot(AI_THINK_TIME,this,SLOT(chessOneByAI()));//ai的思考时间
    }
    else if(game_type ==net)
    {
        chessOneBynet();// ////////////////////////////////////////////////////////chessOneBynet()
    }
}

void MainWindow::chessOneByPerson(){
    if(clickPosRow!=-1 && clickPosCol!=-1 && game->gameMapVec[clickPosRow][clickPosCol]==0)
    {
        //落子
        game->actionByPerson(clickPosRow,clickPosCol);



        update();

    }
}
void MainWindow::chessOneBynet ()
{
    game->actionBynet(clickPosRow,clickPosCol);
    update();
}
void MainWindow::chessOneByAI()
{
    //game->actionByAI(clickPosRow,clickPosCol);
    update();
}


